<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>面试问答</title>
</head>
<script>
	var files = document.getElementById('pic').files; //files是文件选择框选择的文件对象数组

	if (files.length == 0)
		return;

	var form = new FormData(), url = '/image/upload', //服务器上传地址
	file = files[0];
	form.append('file', file);

	var xhr = new XMLHttpRequest();
	xhr.open("post", url, true);

	//上传进度事件
	xhr.upload.addEventListener("progress", function(result) {
		if (result.lengthComputable) {
			//上传进度
			var percent = (result.loaded / result.total * 100).toFixed(2);
		}
	}, false);

	xhr.addEventListener("readystatechange", function() {
		var result = xhr;
		if (result.status != 200) { //error
			console.log('上传失败', result.status, result.statusText,
					result.response);
		} else if (result.readyState == 4) { //finished
			console.log('上传成功', result);
		}
	});
	xhr.send(form); //开始上传
</script>
<body>
	頂頂頂頂頂頂頂頂頂頂頂頂頂頂頂頂
	<input type="file" name="pic" id="pic" accept="image/gif" />
	<form action="/image/upload" enctype="multipart/form-data"
		method="post">
		<p>
			First name: <input type="text" name="fname" />
		</p>
		<p>
			Last name: <input type="file" name="file" />
		</p>
		<input type="submit" value="Submit" />
	</form>
</body>
</html>